package com.ajouroid.smartcoworker;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

/** Get image from url
 * 
 * @author JunYoung Cho
 *
 */

public class GetImageTask extends AsyncTask<String, Integer, Bitmap> {

	ImageView target;
	ProgressBar prog;
	String user_id;
	HashMap<String, Bitmap> f_img_factory;
	HttpConnector conn;
	
	public GetImageTask(ImageView ib, ProgressBar pb)
	{
		target = ib;
		prog = pb;
	}
	
	public GetImageTask(ImageView ib, ProgressBar pb, String user, HashMap<String, Bitmap> map)
	{
		target = ib;
		prog = pb;
		f_img_factory = map;
		user_id = user;
	}
	
	@Override
	protected Bitmap doInBackground(String... params) {
		
		Bitmap bm = null;
		String id = params[0];

		try {
			
			HttpGet get = new HttpGet(HttpConnector.getAddress() + "ProfileImage?id=" + id);
			HttpClient client = new DefaultHttpClient();
			HttpResponse resp = client.execute(get);
			bm = BitmapFactory.decodeStream(resp.getEntity().getContent());
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if(prog != null){
			prog.setVisibility(View.GONE);
		}
		if (result != null)
		{
			Bitmap resize = Bitmap.createScaledBitmap(result, 130, 150, true);
			target.setImageBitmap(resize);
			target.setVisibility(View.VISIBLE);
			
			if(user_id != null){
				f_img_factory.put(user_id, resize);
			}
		}
		super.onPostExecute(result);
	}
	
	

}
